﻿import { getLocalStorage, setLocalStorage } from '@/utils/index'
import {
  loginIn,
  getUserinfo,
  refresh,
  getNewMenuList as getMenuList,
  logout
} from '@/request/api/permissionManagement/user/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
// 初始数据
const state = {
  locale: getLocalStorage('k21ji4jwq82'),
  token: getToken(),
  name: '',
  avatar: '',
  userInfo: {},
  refreshFlag: false // 定义是否正在刷新token
}
// 监听state数据变化(最新状态)
const getters = {
  getLocale (state) {
    return state.locale
  }
}
// 修改state数据
const mutations = {
  saveLocale (state, value) {
    state.locale = value
    setLocalStorage('k21ji4jwq82', value)
  },
  SET_REFRESHFLA (state, info) {
    state.refreshFlag = info
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}
// 触发mutations里的方法
const actions = {
  saveLocale (context, value) {
    context.commit('saveLocale', value)
  },
  setRefreshFlag ({ commit }, info) {
    commit('SET_REFRESHFLA', info)
  },
  // user login
  login ({
    commit
  }, userInfo) {
    return new Promise((resolve, reject) => {
      loginIn(userInfo).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
      //   const data = {
      //     token: 'admin-token'
      //   }
      //   commit('SET_TOKEN', data.token)
      //   setToken(data.token)
    })
  },
  loginSys ({
    commit
  }, userInfo) {
    return new Promise((resolve, reject) => {
      loginIn(userInfo).then(response => {
        commit('SET_TOKEN', JSON.stringify(response.access_token))
        setToken(JSON.stringify(response.access_token))
        response.oprateTime = new Date().getTime()
        localStorage.setItem('ycloud-operate-access_token_obj', JSON.stringify(response))
        sessionStorage.setItem('ycloud-operate-access_token_obj', JSON.stringify(response))
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  refreshToken ({
    commit
  }, info) {
    return new Promise((resolve, reject) => {
      refresh(info).then(response => {
        commit('SET_TOKEN', JSON.stringify(response.access_token))
        setToken(JSON.stringify(response.access_token))
        response.oprateTime = new Date().getTime()
        localStorage.setItem('ycloud-operate-access_token_obj', JSON.stringify(response))
        sessionStorage.setItem('ycloud-operate-access_token_obj', JSON.stringify(response))
        resolve(response)
      })
    })
  },
  // get user info accountType agePeriod  name: "管理员帐号"    id: "100001"  username: "acloud"  state: 0
  getInfo ({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      Promise.all([getUserinfo(), getMenuList()]).then(response => {
        const userInfo = response[0]
        // 生成菜单树
        const menuList = response[1].data[0].children
        if (!userInfo || !menuList) {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject('Verification failed, please Login again.')
        }
        localStorage.setItem('ycloud-operate-user_info', JSON.stringify(userInfo))
        sessionStorage.setItem('ycloud-operate-user_info', JSON.stringify(userInfo))
        commit('SET_NAME', userInfo.username ? userInfo.username : userInfo.name)
        commit('SET_AVATAR', userInfo.photo)
        commit('SET_USER_INFO', userInfo)
        resolve({ userInfo, menuList })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        removeToken()
        // window.localStorage.clear()
        localStorage.removeItem('ycloud-operate-access_token')
        localStorage.removeItem('ycloud-operate-access_token_obj')
        localStorage.removeItem('ycloud-operate-user_info')
        window.sessionStorage.clear()
        // resetRouter()  // 重置路由
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}
export default { state, getters, mutations, actions }
